package com.ruoyi.dm.component.collect;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.constant.CollectFileTypeConstants;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.DataRepeatException;
import com.ruoyi.dm.service.ISpaceEnvCollectRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Component
public class DataCollectService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Autowired
    private ISpaceEnvCollectRecordService collectService;

    //查询 主库最新时间
    public Date queryTime(String tableName,String timeColumn) {
        Date end = jdbcTemplate.queryForObject("SELECT max("+timeColumn+")   FROM "+tableName, Date.class);
        return end;
    }

    //查询 其他库数据
    @DataSource(DataSourceType.SLAVE)
    public List<IndexDataBO> queryData(String sql) {
        List<IndexDataBO> indexDataBOS = jdbcTemplate.query(sql, new RowMapper<IndexDataBO>() {
            @Override
            public IndexDataBO mapRow(ResultSet rs, int rowNum) throws SQLException {
                IndexDataBO bo = new IndexDataBO();
                bo.setIndex(rs.getInt(1));
                bo.setDataTime(rs.getTimestamp(2));
                return bo;
            }
        });
        return indexDataBOS;
    }


    /**
     * 数据是北京时 ,,应转为 utc
     * @param sql
     * @return
     */
    @DataSource(DataSourceType.SLAVE)
    public List<IndexDataBO> queryDataGmt8(String sql) {
        List<IndexDataBO> indexDataBOS = jdbcTemplate.query(sql, new RowMapper<IndexDataBO>() {
            @Override
            public IndexDataBO mapRow(ResultSet rs, int rowNum) throws SQLException {
                IndexDataBO bo = new IndexDataBO();
                bo.setIndex(rs.getInt(1));
                Timestamp dataTime = rs.getTimestamp(2);
                //数据是北京时,需转为utc
                bo.setDataTime(DateUtil.offset(dataTime, DateField.HOUR_OF_DAY,-8));
                return bo;
            }
        });
        return indexDataBOS;
    }

    //调用 数据采集接口
    public void collect(String filePath, String categray, String type) throws DataRepeatException {
        if (CollectFileTypeConstants.TYPE_EARTH.equals(categray) || CollectFileTypeConstants.TYPE_SUN.equals(categray)) {
            collectService.uploadFileByFile(new File[]{new File(filePath)},categray,type);
        }

    }
}
